package org.tloss.web.spring;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

public class ScreenViewResolver extends InternalResourceViewResolver {
	private static final String VIEW_MAPPING_XML = "/viewMapping.xml";
	private Map<String, String> mapping = new HashMap<String, String>();

	public ScreenViewResolver() {
		super();
		ViewMapping viewHolder = JAXB.unmarshal(
				getClass().getResourceAsStream(VIEW_MAPPING_XML),
				ViewMapping.class);
		for (FormMapping view : viewHolder.getFormMappings()) {
			for (View v : view.getViews()) {
				mapping.put(view.getName() + "#" + v.getReturnCase(),
						v.getViewName());
			}
		}
		viewHolder.getFormMappings().clear();
	}

	private String defaultView = null;

	public void setDefaultView(String defaultView) {
		this.defaultView = defaultView;
	}

	protected AbstractUrlBasedView buildView(String viewName) throws Exception {
		if (viewName != null) {
			if (mapping.containsKey(viewName)) {
				viewName = mapping.get(viewName);
				InternalResourceView view = (InternalResourceView) super
						.buildView(viewName);
				return view;
			}
		}
		return defaultView != null ? super.buildView(viewName) : null;

	}
}
